﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using System.Web.Caching;
using System.Web;

namespace MyStore.PresentationModel.Notifications
{
    public class ConfigFileChangeNotifier
    {
        VirtualPathProvider vpp;
        Action<string> changeCallBack;

        private ConfigFileChangeNotifier(Action<string> changeCallBack)
            : this(HostingEnvironment.VirtualPathProvider, changeCallBack)
        {
        }

        private ConfigFileChangeNotifier(VirtualPathProvider vpp, Action<string> changeCallBack)
        {
            this.vpp = vpp;
            this.changeCallBack = changeCallBack;
        }

        public static void Listen(string virtualPath, Action<string> action)
        {
            var notifier = new ConfigFileChangeNotifier(action);
            notifier.ListenForChanges(virtualPath);
        }

        void ListenForChanges(string virtualPath)
        {
            var virtualPathDependencies = new List<string>();
            virtualPathDependencies.Add(virtualPath);

            CacheDependency cacheDependency = vpp.GetCacheDependency(virtualPath, virtualPathDependencies, DateTime.UtcNow);

            HttpRuntime.Cache.Insert(virtualPath, virtualPath, cacheDependency,
                Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable,
                 new CacheItemRemovedCallback(OnConfigFileChanged)
                );
        }

        void OnConfigFileChanged(string key, object value, CacheItemRemovedReason reason)
        {
            if (reason != CacheItemRemovedReason.DependencyChanged)
                return;

            //_changeBack(key);

            ListenForChanges(key);
        }
    }
}
